package com.tencent.iov.cowin.befsale.clue.service.clue.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.software.boot.common.entity.Response;
import com.software.boot.common.exception.BusinessException;
import com.software.boot.common.exception.NEError;
import com.software.boot.common.model.dao.OrderField;
import com.software.boot.common.util.EmptyUtils;
import com.software.common.enums.DeleteEnum;
import com.software.common.utils.BasePropertyInjection;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueIntentionAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueIntentionVehicleAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.AccessAddClueInitialRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.AddClueInitialAfterWashRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.AddClueIntentionVehicleRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.ClueFollowUpRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.DealerCustomerFollowPlanAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.DealerCustomerFollowRecordAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.OemCustomerFollowPlanAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.OemCustomerFollowRecordAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.*;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.response.*;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.MdQueryClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.request.QueryVehicleModelRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.request.QueryVehicleSeriesRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.VehicleModelResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.VehicleSeriesResponse;
import com.tencent.iov.cowin.befsale.clue.dao.kafka.response.ClueRecordRequest;
import com.tencent.iov.cowin.befsale.clue.dao.kafka.response.ClueRecordSyncRequest;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.*;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.DealerCustomer;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.DealerCustomerFollowRecord;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.OemCustomerFollowPlan;
import com.tencent.iov.cowin.befsale.clue.repository.cus.DealerCustomerFollowRecordManager;
import com.tencent.iov.cowin.befsale.clue.repository.cus.DealerCustomerManager;
import com.tencent.iov.cowin.befsale.clue.repository.tenant.TenantManager;
import com.tencent.iov.cowin.befsale.clue.service.clue.*;
import com.tencent.iov.cowin.befsale.clue.service.cus.DealerCustomerFollowPlanService;
import com.tencent.iov.cowin.befsale.clue.service.cus.DealerCustomerFollowRecordService;
import com.tencent.iov.cowin.befsale.clue.service.cus.DealerCustomerService;
import com.tencent.iov.cowin.befsale.clue.service.cus.OemCustomerFollowPlanService;
import com.tencent.iov.cowin.befsale.clue.service.cus.OemCustomerFollowRecordService;
import com.tencent.iov.cowin.befsale.clue.service.cus.OemCustomerService;
import com.tencent.iov.cowin.befsale.clue.value.enums.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @Describe: 线索源信息表_Service实现层
 * @author: whp
 * @created: 2021-12-21 16:16:11
 * @version: 1.0
 */
@Service
@Slf4j
public class ClueSyncServiceImpl implements ClueSyncService {

    @Autowired
    private ClueIntentionService clueIntentionService;
    @Autowired
    private OemCustomerFollowRecordService oemCustomerFollowRecordService;
    @Autowired
    private OemCustomerFollowPlanService oemCustomerFollowPlanService;
    @Autowired
    private DealerCustomerService dealerCustomerService;
    @Autowired
    private OemCustomerService oemCustomerService;
    @Autowired
    private DealerCustomerFollowRecordService dealerCustomerFollowRecordService;
    @Autowired
    private DealerCustomerFollowPlanService dealerCustomerFollowPlanService;
    @Autowired
    private ClueCustomerCollectService clueCustomerCollectService;
    @Autowired
    private ClueIntentionVehicleService clueIntentionVehicleService;
    @Autowired
    private MdQueryClient mdQueryClient;
    @Autowired
    private ClueInitialIntentionVehicleService clueInitialIntentionVehicleService;
    @Autowired
    private DealerCustomerManager dealerCustomerManager;
    @Autowired
    private DealerCustomerFollowRecordManager dealerCustomerFollowRecordManager;
    @Autowired
    private ClueService clueService;
    @Autowired
    private TenantManager tenantManager;

    /**
     * 线索下发--异步执行信息部分
     *
     * @param request
     */
    @Async
    @Override
    public void createClueWithfollowUpSync(ClueFollowUpRequest request,Integer sendType) {
        //线索id
        Long clueId = request.getClueId();
        //线索源经销商id
        String dealerId = request.getDealerId();
        //总部客户id
        Long oemCustomerId = request.getOemCustomerId();
        //经销商客户id
        Long dealerCustomerId = request.getDealerCustomerId();

        //当前时间
        Date crrentDate=new Date();
        //当前时间戳
        Long currentTime=crrentDate.getTime();

        //保存线索的意向信息
        ClueIntention clueIntention = null;
        if (request.getFollowUpClueIntention() != null) {
            clueIntention = ClueIntentionAssembler.transformVOToPO(request.getFollowUpClueIntention(), ClueIntention.class);
            clueIntention.setClueId(clueId);
            clueIntention.setDealerId(dealerId);
            clueIntention.setStatus(com.tencent.iov.cowin.befsale.clue.value.enums.StatusEnum.TEMP_STOR.getCode());
            clueIntention.setDeleted(DeleteEnum.INIT.getFlag());
            clueIntentionService.insert(clueIntention);
        }

        //保存意向品牌等信息
        List<ClueIntentionVehicle> vehList = createIntentionClue(request, clueId);

        //保存计划跟进预约表
        Long oemPlanId = null;
        Long dealerPlanId = null;
        if (request.getFollowUpPlan() != null&& InitalSendTypeEnum.SEND_TYPE_OLD_DATA_SYNC.getCode()!=sendType) {
            if (StringUtils.isEmpty(dealerId) || "0".equals(dealerId)) {
                //保存 计划信息到 bef_oem_customer_follow_plan 表
                OemCustomerFollowPlan oemCustomerFollowPlan = OemCustomerFollowPlanAssembler.transformVOToPO(request.getFollowUpPlan(), OemCustomerFollowPlan.class);
                oemCustomerFollowPlan.setClueId(clueId);
                oemCustomerFollowPlan.setCusId(oemCustomerId);
                //说明线索下发没有计划跟进，则根据需求默认 下次跟进计划时间为：线索分配时间+24小时,第三方对接不需要，第三方没有跟进人
                Date distributeTime= request.getFollowUpClue().getDistributeTime();
                if(distributeTime!=null){
                     Date planFollowTime=new Date(distributeTime.getTime()+24*60*60*1000);
                     oemCustomerFollowPlan.setPlanFollowTime(planFollowTime);
                     oemCustomerFollowPlan.setPlanFollowContent(String.valueOf(FollowContentEnum.PRODUCT_INTRO.getCode()));
                     request.getFollowUpPlan().setPlanFollowTime(planFollowTime);
                     request.getFollowUpPlan().setPlanFollowContent(String.valueOf(FollowContentEnum.PRODUCT_INTRO.getCode()));
                }else{
                     Date planFollowTime=new Date(currentTime+24*60*60*1000);
                     oemCustomerFollowPlan.setPlanFollowTime(planFollowTime);
                     request.getFollowUpPlan().setPlanFollowTime(planFollowTime);
                }
                oemCustomerFollowPlan.setPlanFollowTimeCode(PlanFollowTimeCodeEnum.FOLLOW_TIME_CODE_DAY.getCode());
                request.getFollowUpPlan().setPlanFollowTimeCode(PlanFollowTimeCodeEnum.FOLLOW_TIME_CODE_DAY.getCode());
                //如果下发有试乘试驾，则下次跟进计划为
                if(request.getFollowUpRecord()!=null) {
                    AddOemCustomerFollowRecordRequest followUpRecord=request.getFollowUpRecord();
                    if(followUpRecord.getDriveBrandId()!=null||followUpRecord.getDriveConfigId()!=null||
                        followUpRecord.getDriveModelId()!=null||followUpRecord.getDriveSeriesId()!=null||
                            followUpRecord.getDriveYearId()!=null) {
                        oemCustomerFollowPlan.setPlanFollowContent(String.valueOf(FollowContentEnum.DRIVE_TEST.getCode()));
                        request.getFollowUpPlan().setPlanFollowContent(String.valueOf(FollowContentEnum.DRIVE_TEST.getCode()));
                    }
                }
                oemCustomerFollowPlan.setStatus(FollowPlanStatusEnum.WAIT_FOLLOW.getCode());
                oemCustomerFollowPlanService.insert(oemCustomerFollowPlan);
                oemPlanId = oemCustomerFollowPlan.getId();
            } else {
                //保存 计划信息到 bef_dealer_customer_follow_plan 表
                AddCustomerFollowPlanRequest dealerCustomerFollowPlan = DealerCustomerFollowPlanAssembler.transformVOToPO(request.getFollowUpPlan(), AddCustomerFollowPlanRequest.class);
                dealerCustomerFollowPlan.setClueId(clueId);
                dealerCustomerFollowPlan.setCusId(dealerCustomerId);
                dealerCustomerFollowPlan.setDealerId(dealerId);
                //说明线索下发没有计划跟进，则根据需求默认 下次跟进计划时间为：线索分配时间+24小时 第三方对接不需要，第三方没有跟进人
                Date distributeTime= request.getFollowUpClue().getDistributeTime();
                if(distributeTime!=null){
                    Date planFollowTime=new Date(distributeTime.getTime()+24*60*60*1000);
                    dealerCustomerFollowPlan.setPlanFollowTime(planFollowTime);
                    dealerCustomerFollowPlan.setPlanFollowContent(String.valueOf(FollowContentEnum.PRODUCT_INTRO.getCode()));
                    request.getFollowUpPlan().setPlanFollowTime(planFollowTime);
                    request.getFollowUpPlan().setPlanFollowContent(String.valueOf(FollowContentEnum.PRODUCT_INTRO.getCode()));
                }else{
                    Date planFollowTime=new Date(currentTime+24*60*60*1000);
                    dealerCustomerFollowPlan.setPlanFollowTime(planFollowTime);
                    request.getFollowUpPlan().setPlanFollowTime(planFollowTime);
                }
                dealerCustomerFollowPlan.setPlanFollowTimeCode(PlanFollowTimeCodeEnum.FOLLOW_TIME_CODE_DAY.getCode());
                request.getFollowUpPlan().setPlanFollowTimeCode(PlanFollowTimeCodeEnum.FOLLOW_TIME_CODE_DAY.getCode());
                //如果下发有试乘试驾，则下次跟进计划为
                if(request.getFollowUpRecord()!=null) {
                    AddOemCustomerFollowRecordRequest followUpRecord=request.getFollowUpRecord();
                    if(followUpRecord.getDriveBrandId()!=null||followUpRecord.getDriveConfigId()!=null||
                            followUpRecord.getDriveModelId()!=null||followUpRecord.getDriveSeriesId()!=null||
                            followUpRecord.getDriveYearId()!=null) {
                        dealerCustomerFollowPlan.setPlanFollowContent(String.valueOf(FollowContentEnum.DRIVE_TEST.getCode()));
                        request.getFollowUpPlan().setPlanFollowContent(String.valueOf(FollowContentEnum.DRIVE_TEST.getCode()));
                    }
                }
                dealerCustomerFollowPlan.setStatus(FollowPlanStatusEnum.WAIT_FOLLOW.getCode());
                dealerPlanId = dealerCustomerFollowPlanService.insert(dealerCustomerFollowPlan);
            }
        }

        //第四步： 创建跟进记录信息
        if (request.getFollowUpRecord() != null&&InitalSendTypeEnum.SEND_TYPE_OLD_DATA_SYNC.getCode()!=sendType) {
            BasePropertyInjection.savePropertyInjection(request.getFollowUpRecord());
            if (StringUtils.isEmpty(dealerId) || "0".equals(dealerId)) {
                AddCustomerFollowRecordRequest oemCustomerFollowRecord = OemCustomerFollowRecordAssembler.transformVOToPO(request.getFollowUpRecord(), AddCustomerFollowRecordRequest.class);
                oemCustomerFollowRecord.setClueId(clueId);
                oemCustomerFollowRecord.setCusId(oemCustomerId);
                if(CollectionUtils.isNotEmpty(vehList)) {
                    oemCustomerFollowRecord.setVehInfo(JSON.toJSONString(vehList));
                }
                if (request.getCustomerSourceInfo() != null) {
                    oemCustomerFollowRecord.setSourceInfo(JSON.toJSONString(request.getCustomerSourceInfo()));
                }
                if (clueIntention != null) {
                    oemCustomerFollowRecord.setIntentionTags(clueIntentionService.getClueIntentionStr(clueIntention));
                }
                //企微立即下发，需要如下步骤
                if(InitalSendTypeEnum.SEND_TYPE_QW.getCode()==sendType){
                    //保存 跟进记录到bef_oem_customer_follow_record 表，一次性创建2条；第一条：新建  第二条：分配
                    //第一条是新建
                    oemCustomerFollowRecord.setStatus(FollowRecordStatusEnum.INIT.getCode());
                    oemCustomerFollowRecord.setSecondStatus(FollowRecordSecondStatusEnum.INIT.getCode());
                    oemCustomerFollowRecordService.insert(oemCustomerFollowRecord);
                    //第二条是分配
                    oemCustomerFollowRecord.setId(null);
                    oemCustomerFollowRecord.setStatus(FollowRecordStatusEnum.DISTRIBUTION.getCode());
                    oemCustomerFollowRecord.setSecondStatus(FollowRecordSecondStatusEnum.DISTRIBUTION.getCode());
                    oemCustomerFollowRecord.setNextFollowPlanId(oemPlanId);
                    oemCustomerFollowRecordService.insert(oemCustomerFollowRecord);
                }else{
                    //第三方的，则不需要默认线索历史记录
                    oemCustomerFollowRecord.setStatus(FollowRecordStatusEnum.INIT.getCode());
                    oemCustomerFollowRecord.setSecondStatus(FollowRecordSecondStatusEnum.INIT.getCode());
                    oemCustomerFollowRecord.setId(null);
                    oemCustomerFollowRecord.setNextFollowPlanId(oemPlanId);
                    oemCustomerFollowRecordService.insert(oemCustomerFollowRecord);
                }
            } else {
                //保存 跟进记录到 bef_dealer_customer_follow_record表,一次性创建三条，第一条新建状态，第二条下发状态，第三条分配状态
                AddCustomerFollowRecordRequest dealerCustomerFollowRecord = DealerCustomerFollowRecordAssembler.transformVOToPO(request.getFollowUpRecord(), AddCustomerFollowRecordRequest.class);
                dealerCustomerFollowRecord.setClueId(clueId);
                dealerCustomerFollowRecord.setCusId(dealerCustomerId);
                dealerCustomerFollowRecord.setDealerId(dealerId);
                if(CollectionUtils.isNotEmpty(vehList)) {
                    dealerCustomerFollowRecord.setVehInfo(JSON.toJSONString(vehList));
                }
                if (request.getCustomerSourceInfo() != null) {
                    dealerCustomerFollowRecord.setSourceInfo(JSON.toJSONString(request.getCustomerSourceInfo()));
                }
                if (clueIntention != null) {
                    dealerCustomerFollowRecord.setIntentionTags(clueIntentionService.getClueIntentionStr(clueIntention));
                }
                //跟进人不为空说明是企微创建的，需要如下步骤
                if(InitalSendTypeEnum.SEND_TYPE_QW.getCode()==sendType) {
                    //第一条新建状态
                    dealerCustomerFollowRecord.setStatus(FollowRecordStatusEnum.INIT.getCode());
                    dealerCustomerFollowRecord.setSecondStatus(FollowRecordSecondStatusEnum.INIT.getCode());
                    dealerCustomerFollowRecordService.insert(dealerCustomerFollowRecord);
                    //第二条下发状态
                    dealerCustomerFollowRecord.setStatus(FollowRecordStatusEnum.TRANS.getCode());
                    dealerCustomerFollowRecord.setSecondStatus(FollowRecordSecondStatusEnum.TRANS.getCode());
                    dealerCustomerFollowRecord.setId(null);
                    dealerCustomerFollowRecordService.insert(dealerCustomerFollowRecord);
                    //第三条分配状态
                    dealerCustomerFollowRecord.setStatus(FollowRecordStatusEnum.DISTRIBUTION.getCode());
                    dealerCustomerFollowRecord.setSecondStatus(FollowRecordSecondStatusEnum.DISTRIBUTION.getCode());
                    dealerCustomerFollowRecord.setId(null);
                    dealerCustomerFollowRecord.setNextFollowPlanId(dealerPlanId);
                    dealerCustomerFollowRecordService.insert(dealerCustomerFollowRecord);
                }else{
                    //说明是第三方对接则不需要如上步骤
                    dealerCustomerFollowRecord.setStatus(FollowRecordStatusEnum.INIT.getCode());
                    dealerCustomerFollowRecord.setSecondStatus(FollowRecordSecondStatusEnum.INIT.getCode());
                    dealerCustomerFollowRecord.setId(null);
                    dealerCustomerFollowRecord.setNextFollowPlanId(dealerPlanId);
                    dealerCustomerFollowRecordService.insert(dealerCustomerFollowRecord);
                }
            }
        }
        //保存信息到 搜索宽表
        insertCustomerCollectWithFollowUp(request, dealerId, oemCustomerId, dealerCustomerId, clueId, oemPlanId, dealerPlanId);
    }

    /**
     * add by zly 保存信息到搜索宽表
     *
     * @param request
     * @param dealerId
     * @param oemCustomerId
     * @param dealerCustomerId
     * @param clueId
     * @param oemPlanId
     * @param dealerPlanId
     */
    @Override
    public void insertCustomerCollectWithFollowUp(ClueFollowUpRequest request, String dealerId, Long oemCustomerId, Long dealerCustomerId,
                                                  Long clueId, Long oemPlanId, Long dealerPlanId) {
        //创建宽表对象
        ClueCustomerCollect clueCustomerCollect = new ClueCustomerCollect();
        //初始化宽表基本信息
        clueCustomerCollect.setClueId(clueId);
        clueCustomerCollect.setStatus(InitialStatusEnum.STATUS_DEAL_WITH.getCode());
        //首次新建没有实际跟进为0
        clueCustomerCollect.setFollowNum(0L);
        if (StringUtils.isEmpty(dealerId) || "0".equals(dealerId)) {
            clueCustomerCollect.setCusId(oemCustomerId);
            clueCustomerCollect.setPlanFollowId(oemPlanId);
        } else {
            clueCustomerCollect.setCusId(dealerCustomerId);
            clueCustomerCollect.setPlanFollowId(dealerPlanId);
            clueCustomerCollect.setDealerId(dealerId);
        }
        //宽表线索信息赋值
        if (request.getFollowUpClue() != null) {
            clueCustomerCollect.setClueStatus(request.getFollowUpClue().getStatus());
            clueCustomerCollect.setIntentionGrade(request.getFollowUpClue().getIntentionGrade());
            clueCustomerCollect.setClueCreatedTime(request.getFollowUpClue().getCreatedTime());
            //线索下发经销商时间
            clueCustomerCollect.setCluePlanTime(request.getFollowUpClue().getPlanTime());
            clueCustomerCollect.setDistributeTime(request.getFollowUpClue().getDistributeTime());
            //线索清洗不弄从header里面拿租户信息，所以从线索里面拿
            if(StringUtils.isEmpty(clueCustomerCollect.getTenantId())){
                clueCustomerCollect.setTenantId(request.getFollowUpClue().getTenantId());
            }
            if(StringUtils.isEmpty(clueCustomerCollect.getCorpId())){
                clueCustomerCollect.setCorpId(request.getFollowUpClue().getCorpId());
            }
            clueCustomerCollect.setDealerId(request.getFollowUpClue().getDealerId());
            clueCustomerCollect.setCreatedName(request.getFollowUpClue().getCreatedName());
            clueCustomerCollect.setCreatedBy(request.getFollowUpClue().getCreatedBy());
            clueCustomerCollect.setCreatedTime(request.getFollowUpClue().getCreatedTime());
        }

        //宽表记录信息赋值
        if (request.getFollowUpRecord() != null) {
            //如果新建是有跟进内容的才记录实际跟进字段
            if (EmptyUtils.isNotEmpty(request.getFollowUpRecord().getFollowContent())) {
                clueCustomerCollect.setProdCode(request.getFollowUpRecord().getProdCode());
                clueCustomerCollect.setFollowRemark(request.getFollowUpRecord().getFollowRemark());
                clueCustomerCollect.setFollowTime(new Date());
                clueCustomerCollect.setFollowContent(request.getFollowUpRecord().getFollowContent());
            }
        }

        //宽表计划跟进信息赋值
        if (request.getFollowUpPlan() != null) {
            clueCustomerCollect.setPlanFollowContent(request.getFollowUpPlan().getPlanFollowContent());
            clueCustomerCollect.setPlanFollowTime(request.getFollowUpPlan().getPlanFollowTime());
            clueCustomerCollect.setPlanFollowTimeCode(request.getFollowUpPlan().getPlanFollowTimeCode());
            clueCustomerCollect.setPlanFollowRemark(request.getFollowUpPlan().getPlanFollowRemark());
        }
        //宽表车系品牌等信息为多条，则取第一条维护到宽表作为搜索使用
        if (CollectionUtils.isNotEmpty(request.getAddVehicleList()) && request.getAddVehicleList().size() > 0) {
            AddClueIntentionVehicleRequest inVeRe = request.getAddVehicleList().get(0);
            clueCustomerCollect.setBrandId(inVeRe.getBrandName());
            clueCustomerCollect.setConfigId(inVeRe.getConfigName());
            clueCustomerCollect.setModelId(inVeRe.getModelName());
            clueCustomerCollect.setSeriesId(inVeRe.getSeriesName());
            clueCustomerCollect.setModelYearId(inVeRe.getModelYearName());
        }
        if(StringUtils.isEmpty(request.getExitsFollowEmpName())) {
            clueCustomerCollect.setFollowEmpId(request.getExitsFollowEmpId());
            clueCustomerCollect.setFollowEmpName(request.getExitsFollowEmpName());
        }
        //基本标签，意向标签code-name对应的json信息，后端不处理，仅仅保存入库供前端使用
        clueCustomerCollect.setCodeNameInfo(request.getCodeNameInfo());
        Long collectId = clueCustomerCollectService.insert(clueCustomerCollect);
        sysnCustomerCollection(request, dealerId,collectId );
    }

    public void sysnCustomerCollection(ClueFollowUpRequest request, String dealerId,Long collectId ){
        //同步已入库的客户信息到宽表
        String phone=request.getFollowUpCustomer().getPhone();
        if(StringUtils.isEmpty(phone)){
            return;
        }
        QueryCustomerRequest queryCustomerRequest=new QueryCustomerRequest();
        queryCustomerRequest.setPhone(phone);
        queryCustomerRequest.setFollowEmpId(request.getFollowUpCustomer().getFollowEmpId());
        queryCustomerRequest.setDealerId(dealerId);
        CustomerWithExtResponse cusRes= dealerCustomerService.getCustomerInfoWithPhone(queryCustomerRequest);
        if(cusRes!=null){
            ClueCustomerCollect updateCollectRequest=new ClueCustomerCollect();
            updateCollectRequest.setId(collectId);
            CustomerResponse customerResponse=cusRes.getCustomerResponse();
            CustomerExtResponse customerExtResponse=cusRes.getCustomerExtResponse();
            CustomerBehaviorResponse CustomerBehaviorResponse= cusRes.getCustomerBehaviorResponse();
            if(customerResponse!=null) {
                updateCollectRequest.setName(customerResponse.getName());
                updateCollectRequest.setPhone(customerResponse.getPhone());
                updateCollectRequest.setPhoneBak(customerResponse.getPhoneBak());
                updateCollectRequest.setGender(customerResponse.getGender());
                updateCollectRequest.setTypeCode(customerResponse.getTypeCode());
                updateCollectRequest.setAge(customerResponse.getAge());
                updateCollectRequest.setBirthday(customerResponse.getBirthday());
                updateCollectRequest.setProvinceCode(customerResponse.getProvinceCode());
                updateCollectRequest.setCityCode(customerResponse.getCityCode());
                updateCollectRequest.setDistrictCode(customerResponse.getDistrictCode());
                updateCollectRequest.setAddress(customerResponse.getAddress());
                updateCollectRequest.setQwName(customerResponse.getQwName());
                updateCollectRequest.setCusRemark(customerResponse.getCusRemark());
                updateCollectRequest.setAvatar(customerResponse.getAvatar());
                updateCollectRequest.setFollowEmpId(customerResponse.getFollowEmpId());
                updateCollectRequest.setFollowEmpName(customerResponse.getFollowEmpName());
                updateCollectRequest.setCustomerBaseId(customerResponse.getCustomerBaseId());
                updateCollectRequest.setExternalUserid(customerResponse.getExternalUserid());
                //已绑定好友
                if (EmptyUtils.isNotEmpty(customerResponse.getCustomerBaseId()) && EmptyUtils.isNotEmpty(customerResponse.getExternalUserid())) {
                    updateCollectRequest.setFirendStaus(CustomerFirendStausEnum.BOUND.getCode());

                } else {
                    updateCollectRequest.setFirendStaus(CustomerFirendStausEnum.UNBOUND.getCode());
                }
            }
            if(customerExtResponse!=null){
                updateCollectRequest.setMarriage(customerExtResponse.getMarriage());
            }
            if(CustomerBehaviorResponse!=null) {
                if (StringUtils.isEmpty(dealerId) || "0".equals(dealerId)) {
                    updateCollectRequest.setOemCusBehavior(JSON.toJSONString(CustomerBehaviorResponse));
                } else {
                    updateCollectRequest.setDealerCusBehavior(JSON.toJSONString(CustomerBehaviorResponse));
                }
            }
            clueCustomerCollectService.update(updateCollectRequest);
        }
    }

    /**
     * 保存线索品牌等信息
     * add by zly
     *
     * @param addVehicleList
     * @param clueId
     */
    private List<ClueIntentionVehicle> createIntentionClue( ClueFollowUpRequest request, Long clueId) {
        try {
            List<AddClueIntentionVehicleRequest> addVehicleList=request.getAddVehicleList();
            if (CollectionUtils.isNotEmpty(addVehicleList) && addVehicleList.size() > 0) {
                List<ClueIntentionVehicle> clueIntentionList = new ArrayList<>();
                for (int i = 0; i < addVehicleList.size(); i++) {
                    if (addVehicleList.get(i) instanceof AddClueIntentionVehicleRequest) {
                        AddClueIntentionVehicleRequest clueInRe = addVehicleList.get(i);
                        clueInRe.setClueId(clueId);
                        ClueIntentionVehicle clueIn = ClueIntentionVehicleAssembler.transformVOToPO(clueInRe, ClueIntentionVehicle.class);
                        clueIn.setStatus(StatusEnum.TEMP_STOR.getCode());
                        clueIn.setDeleted(DeleteEnum.INIT.getFlag());
                        clueIn.setTenantId(request.getFollowUpClue().getTenantId());
                        clueIn.setCorpId(request.getFollowUpClue().getCorpId());
                        clueIn.setDealerId(request.getFollowUpClue().getDealerId());
                        clueIn.setCreatedBy(request.getFollowUpClue().getCreatedBy());
                        clueIn.setCreatedName(request.getFollowUpClue().getCreatedName());
                        clueIn.setCreatedTime(request.getFollowUpClue().getCreatedTime());
                        clueIn.setUpdatedBy(request.getFollowUpClue().getUpdatedBy());
                        clueIn.setUpdatedName(request.getFollowUpClue().getUpdatedName());
                        clueIn.setUpdatedTime(request.getFollowUpClue().getUpdatedTime());
                        clueIntentionList.add(clueIn);
                    }
                }
                clueIntentionVehicleService.insertBatch(clueIntentionList);
                return clueIntentionList;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }


    /**
     * add by zly
     * 2022-01-21
     * 线索源意向信息入库--根据车系名称转化对象的id
     * @param request
     * @param initialClueId
     */
   /* @Async*/
    @Override
    public void initClueIntentionVehicle(AddClueInitialAfterWashRequest request, Long initialClueId,String tenantId,String corpId,String dealerId,ClueInitial c) {

        // 凯翼的车型结构是：车系--》年款--》配置
        //          比如：轩度--》2021款--》1.5T手动要得版
        //               炫界--》2021款--》1.5L手动畅享版
        //线索清洗对接只给 车系，比如：轩度，炫界
      //根据车系名称去org表获取车系id
        List<String> seriesNameList= request.getSeriesNameList();
        if(CollectionUtils.isEmpty(seriesNameList)){
            return;
        }

        //先删除已经存在的，
        ClueIntentionVehicle vehicleRequest=new ClueIntentionVehicle();
        vehicleRequest.setClueInitialId(initialClueId);
        Integer count= clueInitialIntentionVehicleService.deleteByParam(vehicleRequest);
        //再添加本次修改的
        if(c.getAddVehicleList()==null){
            c.setAddVehicleList(new ArrayList<>());
        }
        seriesNameList.stream().forEach(s->{
            QueryVehicleSeriesRequest seriesRequest=new QueryVehicleSeriesRequest();
            seriesRequest.setName(s);
            seriesRequest.setTenantId(tenantId);
            seriesRequest.setCorpId(corpId);
            //根据车系名称拿到车系id
            Response<VehicleSeriesResponse> seriesRes=mdQueryClient.getOneSeriesByParam(seriesRequest);
            if(seriesRes!=null&&seriesRes.getData()!=null){
                VehicleSeriesResponse serRes=seriesRes.getData();
                ClueIntentionVehicle iv=new ClueIntentionVehicle();
                iv.setClueInitialId(initialClueId);
                iv.setTenantId(tenantId);
                iv.setCorpId(corpId);
                iv.setDealerId(dealerId);
                iv.setSeriesId(serRes.getId().toString());
                iv.setSeriesName(s);
                iv.setSeriesCode(serRes.getCode());
                clueInitialIntentionVehicleService.insert(iv);
                AddClueIntentionVehicleRequest vehRes=new AddClueIntentionVehicleRequest();
                vehRes.setSeriesId(serRes.getId().toString());
                vehRes.setSeriesName(s);
                vehRes.setSeriesCode(serRes.getCode());
                c.getAddVehicleList().add(vehRes);
            }

        });

    }


    /**
     * add by zly
     * 2022-01-22
     * 线索源意向信息入库--将车型code,车系code转化为对应的id，name
     */
    @Override
    public void initClueIntentionVehicleByCode(List<AccessAddClueInitialRequest.VehicleSeriesAndModelRequest> intentionVehicleList, Long initialClueId, String tenantId, String corpId, String dealerId) {
        if(CollectionUtils.isEmpty(intentionVehicleList)){
            return;
        }
        //再添加本次修改的
        intentionVehicleList.stream().forEach(s->{
            ClueIntentionVehicle iv=new ClueIntentionVehicle();
            //根据车系code拿到车系id和名称--对接org接口
            if(!StringUtils.isEmpty(s.getSeriesCode())) {
                QueryVehicleSeriesRequest seriesRequest = new QueryVehicleSeriesRequest();
                seriesRequest.setCode(s.getSeriesCode());
                seriesRequest.setTenantId(tenantId);
                seriesRequest.setCorpId(corpId);
                Response<VehicleSeriesResponse> seriesRes = mdQueryClient.getOneSeriesByParam(seriesRequest);
                if (seriesRes != null && seriesRes.getData() != null) {
                    VehicleSeriesResponse serRes = seriesRes.getData();
                    iv.setSeriesId(serRes.getId().toString());
                    iv.setSeriesCode(s.getSeriesCode());
                    iv.setSeriesName(serRes.getName());
                }
            }
            //根据车型code 拿到车型id和名称--对接org接口
            if(!StringUtils.isEmpty(s.getModelCode())) {
                QueryVehicleModelRequest modelRequest = new QueryVehicleModelRequest();
                modelRequest.setCode(s.getModelCode());
                modelRequest.setTenantId(tenantId);
                modelRequest.setCorpId(corpId);
                Response<VehicleModelResponse> modelRes = mdQueryClient.getOneModelByParam(modelRequest);
                if (modelRes != null && modelRes.getData() != null) {
                    VehicleModelResponse model = modelRes.getData();
                    iv.setModelId(model.getId().toString());
                    iv.setModelName(model.getName());
                    iv.setModelCode(s.getModelCode());
                }
            }
            iv.setClueInitialId(initialClueId);
            iv.setTenantId(tenantId);
            iv.setCorpId(corpId);
            iv.setDealerId(dealerId);
            clueInitialIntentionVehicleService.insert(iv);
        });
    }

    private void updateClueActualSalesTime(Clue clue, Date receiveDate) {
        if(receiveDate == null){
            return;
        }
        clue.setActualSalesTime(receiveDate);
        clueService.update(clue);
        //宽表
        ClueCustomerCollect collect = new ClueCustomerCollect();
        collect.setClueId(clue.getId());
        collect.setDeliveryCreatedTime(receiveDate);
        clueCustomerCollectService.updateByClueId(collect);
    }

    @Override
    public void handleClueRecord(ClueRecordSyncRequest request) {
        //根据leadId查询线索
        Clue clueParam = new Clue();
        clueParam.setDeleted(DeleteEnum.INIT.getFlag());
        clueParam.setCrmClueId(request.getLeadId());
        clueParam.setOrderFields(Lists.newArrayList(new OrderField("updated_time", "desc")));
        Clue clue = clueService.getOneByParam(clueParam);
        if (Objects.isNull(clue)) {
            log.error("消费CRM的线索离职跟进记录查询线索数据为空，线索ID：【{}】", request.getLeadId());
            throw new BusinessException(NEError.BUSINESS_ERROR, "消费CRM的线索离职跟进记录查询线索数据为空");
        }
        //判读当前线索得状态是否为实销，更新线索表和宽表的实销时间
        if (clue.getStatus().intValue() == ClueStatsEnum.CONSUMED.getCode()) {
            updateClueActualSalesTime(clue, request.getReceiveDate());
        }
        if (CollectionUtils.isEmpty(request.getRecords())) {
            log.error("该线索的跟进记录为空，线索ID：【{}】", request.getLeadId());
            return;
        }
        /*//查询改线索记录是否存在，存在则return，不同步
        DealerCustomerFollowRecord recordParameters = new DealerCustomerFollowRecord();
        recordParameters.setClueId(clue.getId());
        recordParameters.setDeleted(DeleteEnum.INIT.getFlag());
        DealerCustomerFollowRecord followRecord = dealerCustomerFollowRecordManager.getOneByParam(recordParameters);
        if (Objects.nonNull(followRecord)) {
            log.error("消费CRM的线索离职跟进记录查询线索记录不为空，线索ID：【{}】，线索根据记录数据：【{}】", request.getLeadId(), JSON.toJSONString(followRecord));
            //删除原来跟进记录，重新新增新记录
            dealerCustomerFollowRecordManager.deleteByClueId(clue.getId());
        }*/
        //查询dealerCustomer数据
        DealerCustomer dealerCustomer = dealerCustomerManager.getDetailById(clue.getCusId());
        if (Objects.isNull(dealerCustomer)) {
            log.error("消费CRM的线索离职跟进记录查询客户数据为空，线索ID：【{}】，客户ID：【{}】", request.getLeadId(), clue.getCusId());
            throw new BusinessException(NEError.BUSINESS_ERROR, "消费CRM的线索离职跟进记录查询客户数据为空");
        }
        CustomerSourceInfo sourceInfo = new CustomerSourceInfo();
        sourceInfo.setSourceFirst(dealerCustomer.getSourceFirst());
        sourceInfo.setSourceSecond(dealerCustomer.getSourceSecond());
        sourceInfo.setSourceThird(dealerCustomer.getSourceThird());

        //查询客户的意向信息
        ClueIntentionVehicle vehicle = new ClueIntentionVehicle();
        vehicle.setDeleted(DeleteEnum.INIT.getFlag());
        vehicle.setClueId(clue.getId());
        vehicle.setOrderFields(Lists.newArrayList(new OrderField("updated_time", "desc")));
        List<ClueIntentionVehicle> vehicleList = clueIntentionVehicleService.getListByParam(vehicle);


        List<ClueRecordRequest> records = request.getRecords();
        Iterator<ClueRecordRequest> iterator = records.iterator();
        while (iterator.hasNext()){
            ClueRecordRequest clueRecordRequest = iterator.next();
            Boolean lastFlag = false;
            if(!iterator.hasNext()){
                lastFlag = true;
            }
            dealerCustomerFollowRecordService.handleRecord(clueRecordRequest,clue,sourceInfo,vehicleList,dealerCustomer,request,lastFlag);
            iterator.remove();
        }
        //查询线索跟进记录更新宽表的跟进次数
        DealerCustomerFollowRecord followed = new DealerCustomerFollowRecord();
        followed.setDeleted(DeleteEnum.INIT.getFlag());
        followed.setClueId(clue.getId());
        List<DealerCustomerFollowRecord> recordList = dealerCustomerFollowRecordManager.getListByParam(followed);
        Integer followNum = 0;
        if (CollectionUtils.isNotEmpty(recordList)) {
            followNum = recordList.size();
        }
        ClueCustomerCollect collect = new ClueCustomerCollect();
        collect.setClueId(clue.getId());
        collect.setFollowNum(followNum.longValue());
        clueCustomerCollectService.updateByClueId(collect);
    }

    //验证oneId对应的客户是否已经存在其它跟进人，若存在则不允许创建线索
    @Override
    public String checkOneId(String oneId, String dealerId, Long followEmpId, String tenantId, String corpId) {
        return oemCustomerService.checkOneId(oneId, dealerId, followEmpId,tenantId,corpId);
    }
}
